package com.law.lawcaculator.controller;

import com.law.lawcaculator.common.R;
import com.law.lawcaculator.model.dto.GenerateReportResponse;
import com.law.lawcaculator.model.dto.NextFormResponse;
import com.law.lawcaculator.model.dto.SubmitAnswersRequest;
import com.law.lawcaculator.service.FormService;
import com.law.lawcaculator.service.ReportService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletResponse;
import java.util.UUID;

@RestController
@RequestMapping("/api/form")
@RequiredArgsConstructor
public class FormController {

    private final FormService formService;
    private final ReportService reportService;

    @PostMapping("/next")
    public R<NextFormResponse> next(@RequestBody SubmitAnswersRequest request) {
        // 生成或使用现有会话ID
        String sessionId = request.getSessionId();
        if (sessionId == null || sessionId.isEmpty()) {
            sessionId = UUID.randomUUID().toString();
        }
        
        // 使用FormService生成下一步表单
        NextFormResponse response = formService.generateNextForm(sessionId, request.getAnswers());
        return R.ok(response);
    }

    /**
     * 生成法律计算报告
     * @param request 包含会话ID、答案列表和应用ID的请求对象
     * @return 包含报告内容的响应
     */
    @PostMapping("/generate-report")
    public R<GenerateReportResponse> generateReport(@RequestBody SubmitAnswersRequest request) {
        // 生成或使用现有会话ID
        String sessionId = request.getSessionId();
        if (sessionId == null || sessionId.isEmpty()) {
            sessionId = UUID.randomUUID().toString();
        }
        
        // 获取appId并转换为String，默认为null
        // appId将作为calculatorCode存储到数据库中，用于标识不同的应用场景
        String appId = request.getAppId() != null ? String.valueOf(request.getAppId()) : null;
        
        // 生成报告，传递appId作为calculatorCode
        GenerateReportResponse response = reportService.generateReport(sessionId, request.getAnswers(), appId);
        return R.ok(response);
    }

    @GetMapping("/download-report/{sessionId}")
    public void downloadReport(@PathVariable String sessionId, HttpServletResponse response) {
        // 下载Word报告
        reportService.downloadWordReport(sessionId, response);
    }
}



